from django.db import transaction
from rest_framework import serializers

from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification, SpecificationOption, SKUSpecification


class SKUSpecificationSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    # 具体规格序列化器
    class Meta:
        model = SKUSpecification
        fields = ['spec_id', 'option_id']


class SKUSerializer(serializers.ModelSerializer):
    # 商品序列化器
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()

    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)

    specs = SKUSpecificationSerializer(many=True)

    class Meta:
        model = SKU

        fields = '__all__'

    def create(self, validated_data):
        specs_data = validated_data.pop('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)
                for spec_data in specs_data:
                    SKUSpecification.objects.create(sku=sku, **spec_data)
            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_point)
            else:
                transaction.savepoint_commit(save_point)
        return sku

    def update(self, instance, validated_data):
        specs = validated_data.pop('specs')
        super(SKUSerializer, self).update(instance, validated_data)

        for spec in specs:
            SKUSpecification.objects.filter(sku=instance, spec_id=spec.get('spec_id')).update(
                option_id=spec.get('option_id'))
            # print(spec)

        return instance


class GoodsCategorySerializer(serializers.ModelSerializer):
    # 商品类别序列化器
    class Meta:
        model = GoodsCategory
        fields = ['id', 'name']


class SPUSerializer(serializers.ModelSerializer):
    # 商品spu序列化器
    class Meta:
        model = SPU
        fields = ['id', 'name']


class SpecificationOptionModelSerializer(serializers.ModelSerializer):
    # 规格选项序列化器
    class Meta:
        model = SpecificationOption
        fields = ['id', 'spec_id', 'value']


class SpecsModelSerializer(serializers.ModelSerializer):
    # 商品spu规格
    options = SpecificationOptionModelSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = ['id', 'name', 'options']
